////////////////////////////////////////////////////////////////////////////////
// Filename: L_dx11vertexbuffer.cpp
////////////////////////////////////////////////////////////////////////////////
#include "L_dx11vertexbuffer.h"

L_DX11VertexBuffer::L_DX11VertexBuffer()
{
	Buffer = 0;
}

L_DX11VertexBuffer::~L_DX11VertexBuffer()
{

}

bool L_DX11VertexBuffer::Init(ID3D11Device* Device, void* Data, unsigned int tSize, bool tStatic)
{
	HRESULT hr;

	Static = tStatic;
	Size = tSize;

	D3D11_BUFFER_DESC vertexBufferDesc;
	ZeroMemory( &vertexBufferDesc, sizeof(vertexBufferDesc) );


	if(Static)
	{
		vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
		vertexBufferDesc.CPUAccessFlags = 0;
	}
	else
	{
		vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
		vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	}	
	vertexBufferDesc.ByteWidth = Size;
	vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	vertexBufferDesc.MiscFlags = 0;
	vertexBufferDesc.StructureByteStride = 0;

	D3D11_SUBRESOURCE_DATA vertexBufferData;
	ZeroMemory( &vertexBufferData, sizeof(vertexBufferData) );
	vertexBufferData.pSysMem = Data;

	hr = Device->CreateBuffer( &vertexBufferDesc, &vertexBufferData, &Buffer);
	if(FAILED(hr))
	{
		MessageBox(NULL, "Error creating buffer", "Error", MB_OK | MB_ICONERROR);
		return false;
	}

	return true;
}

bool L_DX11VertexBuffer::Update(ID3D11DeviceContext* DeviceContext, void* Data, unsigned int tSize, unsigned int Offset)
{
	HRESULT hr;
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	hr = DeviceContext->Map(Buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
	if( FAILED(hr) )
	{
		MessageBox(NULL, "Error mapping resource", "Error", MB_OK | MB_ICONERROR);
		return false;
	}

	memcpy(mappedResource.pData, Data, tSize);

	DeviceContext->Unmap(Buffer, 0);

	return true;
}

void L_DX11VertexBuffer::Release()
{

}

ID3D11Buffer* L_DX11VertexBuffer::GetBuffer()
{
	return Buffer;
}

unsigned int L_DX11VertexBuffer::GetSize()
{
	return Size;
}